package com.yang.sso.oauth.controller;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.yang.sso.oauth.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公钥接口
 * @author: Islands
 * @create: 2024-03-23 15:35
 */
@Slf4j
@RestController
@RequestMapping("/rsa")
@RequiredArgsConstructor
public class RsaController {

    private final KeyPair keyPair;

    public static final String PUBLIC_KEY = "publicKey.key";

    /**
     * 获取公钥
     * @return Map<String, Object>
     */
    @GetMapping("/publicKey")
    public Result<Map<String, Object>> getPublicKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return Result.success(new JWKSet(key).toJSONObject());
    }

    /**
     * 获取本地公钥
     * @return Result<String>
     */
    @GetMapping("/localKey")
    public Result<String> getLocalKey(){
        try {
            Resource resource = new ClassPathResource(PUBLIC_KEY);
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return Result.success(br.lines().collect(Collectors.joining("\n")));
        }catch (IOException e) {
            log.error("获取本地公钥失败:{}",e.getMessage());
            return Result.failed("获取失败");
        }

    }

}
